<template>
  <div>
    <Breadcrumb :style="{margin: '16px 0'}">
      <BreadcrumbItem>首页</BreadcrumbItem>
      <BreadcrumbItem to="/role">角色管理</BreadcrumbItem>
      <BreadcrumbItem>添加角色</BreadcrumbItem>
    </Breadcrumb>
    <Card>
      <div style="min-height: 600px">
        <Row>
          <Col span="12" offset="6">
            <Form>
              <FormItem label="角色名称">
                <Input type="text" v-model="roleName" placeholder="请输入角色名称" />
              </FormItem>
            </Form>
            <Divider></Divider>
          </Col>
          <Col span="12" offset="6">
            <Tree :data="treeData" @on-check-change="checkChange" show-checkbox check-strictly></Tree>
            <Divider></Divider>
          </Col>
          <Col span="12" offset="6">
            <Button type="primary" size="large" @click="handleSubmit">提交</Button>
          </Col>
        </Row>
      </div>
    </Card>
  </div>
</template>

<script>
const qs = require('qs')
export default {
  data() {
    return {
      roleName: "",
      treeData: [],
      tree: [],
      perms: [],
      permarr: []
    }
  },
  methods: {
    checkChange(n, m) {
      let permarr = []
      n.forEach(item => {
        permarr.push(item.id)
      })

      this.perms = permarr
    },
    handleSubmit() {
      this.$axios.post('/bm/opera/role/updateRole', qs.stringify({
        roleName: this.roleName,
        permIds: this.perms.toString(),
        roleId: this.$route.query.id
      })).then(res => {
        if (res.data.code == 200) {
          this.$Message.success('角色修改成功！')
          this.$router.replace('/role')
        } else {
          this.$Message.error(res.data.description)
        }
      }).catch(err => {
        this.$Message.error('网络连接错误，请稍后重试！')
      })
    },
    getAuthList(_this) {
      _this.$axios.get('/bm/opera/role/findAllPermList').then(res => {
        if (res.data.code == 200) {
          _this.treeData = formatTree(res.data.detail, _this.permarr)
        }
      })
    }
  },
  mounted() {
    this.roleName = this.$route.query.name,
    this.permarr = this.$route.query.perm ? this.$route.query.perm.split(',') : []

    this.$options.methods.getAuthList(this)

  }
}
function formatTree(subdata, permarr) {
  let arr = [];
  subdata.forEach((item, index) => {
    let subarr = {};
    subarr = {
      title: item.name,
      id: item.id,
      pid: item.pid,
      perms: item.perms,
      type: item.type,
      url: item.url,
      expand: true,
      checked: permarr.indexOf(item.name) == -1 ? false : true
    };

    if (item.sonPermList.length > 0) {
      subarr.disabled = true
      subarr.children = formatTree(item.sonPermList, permarr);
    }

    arr.push(subarr);
  });

  return arr;
}
</script>
